﻿using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Sgr.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sgr.Tests
{
    public class SgrWebApplicationFactory<TProgram> : WebApplicationFactory<TProgram> where TProgram : class
    {
        protected override IHost CreateHost(IHostBuilder builder)
        {
            //https://github.com/dotnet-architecture/eShopOnWeb/issues/465

            ConfigureHostEnvironment(builder);

            var host = builder.Build();
            host.Start();

            PrepareHost(host);

            return host;
        }

        protected virtual void ConfigureHostEnvironment(IHostBuilder builder)
        {
            //builder.UseEnvironment("Development");
            //builder.UseEnvironment("Production");
        }

        public override async ValueTask DisposeAsync()
        {
            await CleanupHost(Services);
            await base.DisposeAsync();
            GC.SuppressFinalize(this);
        }

        protected virtual Task CleanupHost(IServiceProvider serviceProvider)
        {
            return Task.CompletedTask;
        }

        /// <summary>
        /// 完成测试前所需的准备工作
        /// </summary>
        /// <param name="host"></param>
        protected virtual void PrepareHost(IHost host)
        {
        }
    }
}